

from .log import log_info, log_error, log_success, log_warning
from .utils import random_string, random_password

import requests
import time
import re
import random
MAILTM_API = ""
# 配置 Mail.tm 和 Mail.gw 的 API 地址
MAIL_SERVICES = [
    {"name": "Mail.tm", "api": "https://api.mail.tm"},
    {"name": "Mail.gw", "api": "https://api.mail.gw"}
]

SESSION = requests.Session()  # 使用会话复用连接

def get_domain(api_url):
    """获取可用域名"""
    try:
        resp = SESSION.get(f"{api_url}/domains")
        resp.raise_for_status()
        domains = resp.json().get("hydra:member", [])
        if domains:
            domain = domains[0]["domain"]
            return domain, None
        else:
            return None, f"{api_url} 未返回可用域名"
    except requests.exceptions.RequestException as e:
        return None, f"获取域名失败: {e}"

def create_account(api_url, domain):
    """在指定服务上创建邮箱账号"""
    address = f"{random_string(12)}@{domain}"
    password = random_password(12)
    try:
        resp = SESSION.post(f"{api_url}/accounts", json={"address": address, "password": password})
        if resp.status_code == 201:  # Created
            return {"address": address, "password": password}, None
        elif resp.status_code == 422:  # Address already exists
            return {"address": address, "password": password}, "地址已存在"
        else:
            return None, f"创建账号失败，状态码: {resp.status_code}, 响应: {resp.text}"
    except requests.exceptions.RequestException as e:
        return None, f"创建账号请求失败: {e}"

def get_token(api_url, address, password):
    """获取 Token"""
    try:
        resp = SESSION.post(f"{api_url}/token", json={"address": address, "password": password})
        resp.raise_for_status()
        token_data = resp.json()
        token = token_data.get("token")
        if token:
            return token, None
        else:
            return None, f"{api_url} 未返回 Token"
    except requests.exceptions.RequestException as e:
        return None, f"获取 Token 请求失败: {e}"

def create_mail_account_with_fallback():
    global MAILTM_API
    """尝试使用多个服务创建临时邮箱"""
    for service in MAIL_SERVICES:
        service_name = service["name"]
        api_url = service["api"]
        MAILTM_API = service["api"]
        log_info(f"尝试使用 {service_name} 创建临时邮箱...")

        # 获取域名
        domain, domain_err = get_domain(api_url)
        if domain_err:
            log_error(f"{service_name} 获取域名失败: {domain_err}")
            continue  # 尝试下一个服务

        # 创建账户
        account, account_err = create_account(api_url, domain)
        if account_err:
            log_error(f"{service_name} 创建账号失败: {account_err}")
            continue  # 尝试下一个服务

        # 获取 Token
        token, token_err = get_token(api_url, account["address"], account["password"])
        if token_err:
            log_error(f"{service_name} 获取 Token 失败: {token_err}")
            continue  # 尝试下一个服务

        # 成功创建账号并获取 Token
        log_info(f"{service_name} 创建成功: {account['address']}")
        return account["address"], account["password"], token, None

    # 所有服务均失败
    return None, None, None, "所有服务均无法创建临时邮箱"

# 邮箱轮询
def poll_mail_code(token, max_retries=15, delay=5):
    """Polls Mail.tm for a message containing a 6-digit code."""
    if not token:
        log_error("无法轮询邮件，Token无效")
        return None, "Token无效"

    headers = {"Authorization": f"Bearer {token}"}
    log_info("开始轮询验证码邮件...")

    for i in range(max_retries):
        log_info(f"轮询邮件第 {i+1}/{max_retries} 次...")
        try:
            resp = SESSION.get(f"{MAILTM_API}/messages", headers=headers, timeout=10)
            resp.raise_for_status()
            messages = resp.json().get("hydra:member", [])

            if messages:
                latest_msg = messages[0] # Assume latest is the first
                msg_id = latest_msg.get("id")
                subject = latest_msg.get("subject", "无主题")
                log_success(f"收到邮件: '{subject}' (ID: {msg_id})")

                # Fetch message details
                detail_resp = SESSION.get(f"{MAILTM_API}/messages/{msg_id}", headers=headers, timeout=10)
                detail_resp.raise_for_status()
                msg_detail = detail_resp.json()
                text_content = msg_detail.get("text") or msg_detail.get("html") or ""

                # Extract 6-digit code
                match = re.search(r"\b(\d{6})\b", text_content)
                if match:
                    code = match.group(1)
                    log_success(f"🎯 从邮件中提取到验证码: {code}")
                    return code, None # Success
                else:
                    log_warning(f"邮件 '{subject}' 中未找到6位验证码。内容片段: {text_content[:100]}...")
                    # Continue polling even if this mail didn't have the code

            else:
                log_info("邮箱中无新邮件")

        except requests.exceptions.RequestException as e:
            log_error(f"轮询邮件时请求失败: {e}")
            # Don't immediately fail, maybe temporary network issue
        except Exception as e:
            log_error(f"处理邮件时发生未知错误: {e}")
            # Don't immediately fail

        time.sleep(delay)

    log_error(f"轮询超时 ({max_retries}次)，未找到验证码邮件")
    return None, "轮询超时未找到验证码"
